/**
 * 登录页面
 * 
 * 用户登录界面
 */

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Database, Eye, EyeOff, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useUserStore, useNotificationStore } from '@/store'
import { authApi } from '@/services/api'

const LoginPage: React.FC = () => {
  const navigate = useNavigate()
  const { setUser, setToken } = useUserStore()
  const { addNotification } = useNotificationStore()
  
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.username || !formData.password) {
      addNotification({
        type: 'error',
        title: '登录失败',
        message: '请输入用户名和密码'
      })
      return
    }

    setLoading(true)
    
    try {
      // 模拟登录API调用
      // const result = await authApi.login(formData.username, formData.password)
      
      // 模拟登录成功
      const mockUser = {
        id: '1',
        username: formData.username,
        email: `${formData.username}@example.com`,
        displayName: formData.username === 'admin' ? '系统管理员' : '用户',
        role: formData.username === 'admin' ? 'admin' as const : 'developer' as const,
        avatar: undefined,
        createdAt: new Date().toISOString(),
        lastLoginAt: new Date().toISOString()
      }
      
      const mockToken = 'mock-jwt-token-' + Date.now()
      
      // 设置用户信息和token
      setUser(mockUser)
      setToken(mockToken)
      
      // 保存token到localStorage
      localStorage.setItem('auth-token', mockToken)
      
      addNotification({
        type: 'success',
        title: '登录成功',
        message: `欢迎回来，${mockUser.displayName}！`
      })
      
      // 跳转到仪表板
      navigate('/dashboard')
      
    } catch (error) {
      addNotification({
        type: 'error',
        title: '登录失败',
        message: error instanceof Error ? error.message : '登录过程中发生错误'
      })
    } finally {
      setLoading(false)
    }
  }

  // 处理输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-gray-900 dark:to-gray-800">
      <div className="max-w-md w-full space-y-8 p-8">
        {/* 登录卡片 */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-8">
          {/* 头部 */}
          <div className="text-center mb-8">
            <div className="flex justify-center mb-4">
              <div className="w-16 h-16 bg-primary rounded-xl flex items-center justify-center">
                <Database className="w-8 h-8 text-primary-foreground" />
              </div>
            </div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
              数据网关管理平台
            </h1>
            <p className="text-gray-600 dark:text-gray-400 mt-2">
              请登录您的账户以继续
            </p>
          </div>

          {/* 登录表单 */}
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* 用户名输入 */}
            <div>
              <label htmlFor="username" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                用户名
              </label>
              <input
                id="username"
                name="username"
                type="text"
                required
                value={formData.username}
                onChange={handleInputChange}
                className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                placeholder="请输入用户名"
                disabled={loading}
              />
            </div>

            {/* 密码输入 */}
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                密码
              </label>
              <div className="relative">
                <input
                  id="password"
                  name="password"
                  type={showPassword ? 'text' : 'password'}
                  required
                  value={formData.password}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
                  placeholder="请输入密码"
                  disabled={loading}
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  disabled={loading}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4 text-gray-400" />
                  ) : (
                    <Eye className="h-4 w-4 text-gray-400" />
                  )}
                </button>
              </div>
            </div>

            {/* 记住我选项 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <input
                  id="remember"
                  name="remember"
                  type="checkbox"
                  className="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded"
                  disabled={loading}
                />
                <label htmlFor="remember" className="ml-2 block text-sm text-gray-700 dark:text-gray-300">
                  记住我
                </label>
              </div>
              <div className="text-sm">
                <a href="#" className="text-primary hover:text-primary/80">
                  忘记密码？
                </a>
              </div>
            </div>

            {/* 登录按钮 */}
            <Button
              type="submit"
              className="w-full"
              disabled={loading}
              loading={loading}
            >
              {loading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  登录中...
                </>
              ) : (
                '登录'
              )}
            </Button>
          </form>

          {/* 演示账户提示 */}
          <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
            <h3 className="text-sm font-medium text-blue-800 dark:text-blue-200 mb-2">
              演示账户
            </h3>
            <div className="text-xs text-blue-600 dark:text-blue-300 space-y-1">
              <div>管理员: admin / admin</div>
              <div>开发者: developer / developer</div>
              <div>查看者: viewer / viewer</div>
            </div>
          </div>
        </div>

        {/* 页脚 */}
        <div className="text-center text-sm text-gray-500 dark:text-gray-400">
          <p>© 2024 数据网关管理平台. 保留所有权利.</p>
          <p className="mt-1">
            基于 React + TypeScript + Rust 构建
          </p>
        </div>
      </div>
    </div>
  )
}

export default LoginPage
